﻿using CaseManagerLibrary.Log;
using CaseManagerLibrary.Models;
using PSDLib.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static PSDLib.Download.DPSDK;

namespace PSDLib.Download
{
    public class DH_8900_Downloader : IDownloader
    {
        public IntPtr nPDLLHandle { get; set; } = IntPtr.Zero;
        public string Id { get; set; }
        public dl_files FileInfo { get; set; }
        public ILog Logger { get; set; }
        public IDownloadServer DownloadServer { get; set; }
        public ConsoleProgressBar ProgressBar { get; set; }

        public event UpdateDownloadProgressEventHandler UpdateDownloadProgress;
        public event FileDownloadCompletedEventHandler FileDownloadSuccess;
        public event FileDownloadCompletedEventHandler FileDownloadFail;
        public event ResetSessionEventHandler ResetSession;

        public int downloadSeq = 0;

        private System.Timers.Timer progressTimer;
        private long lastFileSize = 0;

        public DH_8900_Downloader()
        {
            progressTimer = new System.Timers.Timer();
            progressTimer.Interval = 1000 * 60;
            progressTimer.Enabled = false;
            progressTimer.Elapsed += ProgressTimer_Elapsed;
        }

        public HResult Download(dl_files file)
        {
            HResult result = new HResult() { success = false };

            FileInfo = file;
            FileInfo.dl_progress = 0;

            try
            {
                (DownloadServer as DH8900DownloadServer).downlaoderList.Add(this);
                ;
                string szCameraId = file.channel_id;//"1002059$1$0$1";

                dpsdk_recsource_type_e nSource = dpsdk_recsource_type_e.DPSDK_CORE_PB_RECSOURCE_PLATFORM; //中心录像-云存储
                //dpsdk_recsource_type_e nSource = dpsdk_recsource_type_e.DPSDK_CORE_PB_RECSOURCE_DEVICE; //设备录像-审讯主机

                UInt64 uBeginTime = Convert.ToUInt64(file.video_start_time.Subtract(Convert.ToDateTime("1970-1-1 8:00:00")).TotalSeconds);
                UInt64 uEndTime = Convert.ToUInt64(file.video_end_time.Subtract(Convert.ToDateTime("1970-1-1 8:00:00")).TotalSeconds);

                if (!System.IO.Directory.Exists(file.file_path))
                {
                    System.IO.Directory.CreateDirectory(file.file_path);
                }

                string fileName = System.IO.Path.Combine(file.file_path, file.file_name);

                //file_type_e fileType = System.IO.Path.GetExtension(FileInfo.file_name).ToLower() == ".mp4" ? file_type_e.FILE_TYPE_MP4 : file_type_e.FILE_TYPE_NONE;

                IntPtr ret = DPSDK.DPSDK_DownloadRecordByTime(nPDLLHandle, out downloadSeq, Encoding.UTF8.GetBytes(szCameraId), nSource, uBeginTime, uEndTime, Encoding.Default.GetBytes(fileName), (IntPtr)30000);

                if (ret != IntPtr.Zero)
                {
                    //MessageBox.Show("按时间下载MP4失败，错误码：" + result.ToString());

                    result.success = false;
                    string error = Enum.ToObject(typeof(DH8900ErrorCode), ret.ToInt32()).ToString();
                    result.message = "调用DPSDK_DownloadRecordByTime失败，" + error + "，错误代码=" + ret.ToInt32().ToString();
                }
                else
                {
                    //MessageBox.Show("按时间下载MP4开始");
                    result.success = true;
                }
            }
            catch (Exception ex)
            {
                result.success = false;
                result.message = ex.Message;
            }

            return result;
        }

        private void ProgressTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (lastFileSize == FileInfo.file_size)
            {
                Logger.Log("DPSDK.DPSDK_DownloadRecordByTimeEx no response");
                Stop();
                FileInfo.error_log = "获取连接Session信息";
                FileInfo.state = 2;
                FinishDownload(false);
            }
            else
            {
                lastFileSize = FileInfo.file_size;
            }
        }

        public void UpdateProgress(int position)
        {
            if (position < 100 && position >= 0)
            {
                FileInfo fi = new FileInfo(Path.Combine(FileInfo.file_path, FileInfo.file_name));

                FileInfo.file_size = fi.Length;

                FileInfo.dl_progress = position;

                int diff = Convert.ToInt32((DateTime.Now - FileInfo.dl_start_time.Value).TotalSeconds);

                if (diff > 0)
                {
                    FileInfo.dl_speed = FileInfo.file_size / diff;
                }

                UpdateDownloadProgress(this, FileInfo, diff);
            }
        }

        public void FinishDownload(bool success)
        {
            progressTimer.Enabled = false;
            FileInfo.dl_end_time = DateTime.Now;
            FileInfo.state = (success ? 1 : 2);

            System.Threading.Thread.Sleep(1000 * 2);

            //Logout();

            if (success)
            {
                FileDownloadSuccess(this, FileInfo);
            }
            else
            {
                FileDownloadFail(this, FileInfo);
            }

            (DownloadServer as DH8900DownloadServer).downlaoderList.Remove(this);
        }

        public void ResetSessionInfo(params object[] args)
        {
            if (args.Length == 1)
            {
                nPDLLHandle = (IntPtr)args[0];
            }
        }

        public HResult Stop()
        {
            HResult result = new HResult();

            if (downloadSeq > 0)
            {
                try
                {
                    var ret = DPSDK.DPSDK_StopDownloadRecord(nPDLLHandle, downloadSeq);

                    if (ret != IntPtr.Zero)
                    {
                        if (ret == (IntPtr)1009001)
                        {
                            result.message = "该时间段没有录像";
                            Logger.Error("停止下载文件，该时间段没有录像");

                        }
                        else
                        {
                            result.message = ret.ToString();
                            Logger.Error("停止下载文件失败：" + (FileInfo == null ? "" : FileInfo.file_name) + " - " + result.message);
                        }

                        result.success = false;
                    }
                    else
                    {
                        result.success = true;
                        Logger.Log("停止下载文件：" + (FileInfo == null ? "" : FileInfo.file_name));
                        downloadSeq = 0;
                    }
                }
                catch (Exception ex)
                {
                    result.success = false;
                    result.message = ex.Message;
                }
            }
            else
            {
                result.success = false;
                result.message = "该时间段没有录像";
            }

            return result;
        }
    }
}
